package com.xiaoyun.seleniumlinux.config.mq;

import cn.hutool.core.util.RandomUtil;
import com.xiaoyun.seleniumlinux.enums.MqConstants;
import com.xiaoyun.seleniumlinux.pojo.MessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;


/**
 * @author Xiaoyun461
 */
@Service
@Slf4j
public class RabbitMessageServiceImpl implements IRabbitMessageService, RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate() {
        //消息发送失败返回到队列中, yml需要配置 publisher-returns: true
        rabbitTemplate.setMandatory(true);
        //消息消费者确认收到消息后，手动ack回执
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }


    @Override
    public void sendMessage(MessageDTO msg) {
        CorrelationData correlationData = new CorrelationData();
        String id = RandomUtil.randomString(16);
        correlationData.setId(id);
        //发送消息
        rabbitTemplate.convertSendAndReceive(MqConstants.EXCHANGE_SELENIUM_SUCCESS, "", msg, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            //消息成功到达交换机
            log.info("{}爬虫消息完成到达交换机", correlationData.getId());
        } else {
            log.error("{}爬虫消息未到达交换机,原因：{}", correlationData.getId(), cause);
        }

    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.error("{}消息未到达队列", returned.toString());
    }

}
